package com.atguigu.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.Arrays;
import java.util.UUID;

/**
 * Date:2020/9/30
 * Author:ybc
 * Description:
 */
@Controller
public class FileController {

    @RequestMapping("/down")
    public ResponseEntity<byte[]> down(HttpSession session) throws IOException {
        ServletContext servletContext = session.getServletContext();
        InputStream resourceAsStream = servletContext.getResourceAsStream("/static/css/img/body1.jpg");
        byte[] body = new byte[resourceAsStream.available()] ;
        resourceAsStream.read(body);
        MultiValueMap<String, String> headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment;filename=1.jpg");
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(body, headers, statusCode);
        return responseEntity ;
    }

    @RequestMapping("/up")
    public String up(MultipartFile photo, HttpServletRequest request, String hobby) throws IOException {
        System.out.println(hobby);
        String fileName = photo.getOriginalFilename();
        String hzName = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID().toString().replaceAll("-","") + hzName;

        String photoPath = request.getServletContext().getRealPath("photo");
        File file = new File(photoPath);
        if(!file.exists()){
            file.mkdir();
        }
        String finalPath = photoPath + File.separator + fileName;
        photo.transferTo(new File(finalPath));
        /*InputStream is = photo.getInputStream();
        OutputStream os = new FileOutputStream(finalPath);*/

        return "forward:/success.jsp";
    }

}
